#-*- coding: utf-8 -*-
import traceback, sys, cStringIO
import datetime, time, cgi
import pytz, re
from django.conf import settings

from BeautifulSoup import BeautifulSoup

def get_err():
    f = cStringIO.StringIO( )
    traceback.print_exc(file=f)
    return f.getvalue( )

def print_err():
    sys.stderr.write('err time: '+str(datetime.datetime.utcnow()))
    traceback.print_exc(file=sys.stderr)

def gbk2utf8(s):
    if type(s) == unicode:
        return s.encode('utf8')
    return s.decode('gb18030').encode('utf8')

def utf82gbk(s):
    if type(s) == unicode:
        return s.encode('gb18030')
    return s.decode('utf8').encode('gb18030')

def get_mod(module_name):
    mod = __import__(module_name)
    
    components = module_name.split('.')
    for comp in components[1:]:
        mod = getattr(mod, comp)
    
    return mod

def escape_dict(d):
    for k in d:
        if isinstance(d[k], str):
            d[k] = cgi.escape(d[k])
    return d

def ipdumps(ip):
    if ip:
        p = [int(a) for a in ip.split('.')]
        return p[3]+ p[2]*256+ p[1]*256*256+ p[0]*256*256*256
    else:
        return None

def process_html(html):
    code_tag = re.compile('\s*<pre name="code" class="([^"]+)">', 
                          re.MULTILINE)

    soup = BeautifulSoup(html)
    clean_html = ''
    for section in soup.contents:
        txt = unicode(section)
        matchobj = re.match(code_tag, txt)
        if matchobj:
            clean_html += re.sub(r'<br />', "\n", txt)
        else:
            clean_html += txt
    
    return clean_html